using AutoMapper;
using MediatR;
using SqlSugar;
using TaskProject.Application.Command.Plan;
using TaskProject.Domain.Plan;
using TaskProject.ErrorCode;
using TaskProject.Extension.Plan;
using TaskProject.InfrasIntructure.Implement;

namespace TaskProject.Application.Handler.Plan
{
    /// <summary>
    /// 获取生产计划操作记录处理器
    /// </summary>
    public class GetProductionPlanOperationLogsHandler : IRequestHandler<GetProductionPlanOperationLogsCommand, APIResult<List<ProductionPlanOperationLogDTO>>>
    {
        private readonly DatabaseContext _db;
        private readonly IMapper _mapper;

        public GetProductionPlanOperationLogsHandler(DatabaseContext db, IMapper mapper)
        {
            _db = db;
            _mapper = mapper;
        }

        public async Task<APIResult<List<ProductionPlanOperationLogDTO>>> Handle(GetProductionPlanOperationLogsCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<List<ProductionPlanOperationLogDTO>>();

            try
            {
                // 检查生产计划是否存在
                var productionPlan = await _db.sqlSugar.Queryable<ProductionPlanModel>()
                    .Where(p => p.PlanId == request.PlanId && !p.IsDel)
                    .AnyAsync(cancellationToken);

                if (!productionPlan)
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = "生产计划不存在";
                    return result;
                }

                // 构建查询条件
                var query = _db.sqlSugar.Queryable<ProductionPlanOperationLogModel>()
                    .Where(l => l.PlanId == request.PlanId);

                // 添加操作类型筛选
                if (request.OperationType.HasValue)
                {
                    query = query.Where(l => l.OperationType == request.OperationType.Value);
                }

                // 添加时间范围筛选
                if (request.StartTime.HasValue)
                {
                    query = query.Where(l => l.OperationTime >= request.StartTime.Value);
                }

                if (request.EndTime.HasValue)
                {
                    query = query.Where(l => l.OperationTime <= request.EndTime.Value);
                }

                // 添加操作人筛选
                if (!string.IsNullOrEmpty(request.OperatorName))
                {
                    query = query.Where(l => l.OperatorName.Contains(request.OperatorName));
                }

                // 获取操作记录列表
                var operationLogs = await query
                    .OrderByDescending(l => l.OperationTime)
                    .ToListAsync(cancellationToken);

                // 转换为DTO
                var logDTOs = new List<ProductionPlanOperationLogDTO>();
                foreach (var log in operationLogs)
                {
                    var logDTO = new ProductionPlanOperationLogDTO
                    {
                        LogId = log.LogId,
                        PlanId = log.PlanId,
                        OperationType = log.OperationType,
                        OperationTypeName = log.OperationTypeName,
                        OperationDescription = log.OperationDescription,
                                                 BeforeStatus = log.BeforeStatus,
                         BeforeStatusName = GetPlanStatusName(log.BeforeStatus),
                         AfterStatus = log.AfterStatus,
                         AfterStatusName = log.AfterStatus.HasValue ? GetPlanStatusName(log.AfterStatus.Value) : "未知状态",
                        OperatorName = log.OperatorName,
                        OperationTime = log.OperationTime,
                        IpAddress = log.IpAddress,
                        Remarks = log.Remarks
                    };
                    logDTOs.Add(logDTO);
                }

                result.Code = APIEnum.Success;
                result.Msg = "获取成功";
                result.Data = logDTOs;
            }
            catch (Exception ex)
            {
                result.Code = APIEnum.Fail;
                result.Msg = $"获取失败：{ex.Message}";
            }

            return result;
        }

        /// <summary>
        /// 获取计划状态名称
        /// </summary>
        private string GetPlanStatusName(int status)
        {
            return status switch
            {
                0 => "草稿",
                1 => "已确认",
                2 => "执行中",
                3 => "已完成",
                4 => "已取消",
                _ => "未知状态"
            };
        }
    }
} 